#include "stdafx.h"
#include "BuddylistPanel.h"
#include "IBuddylist.h"
#include "AccountInfoMgr.h"
#include "ChatFrameMgr.h"

#include "UIDef.h"

CBuddylistPanel::CBuddylistPanel(void)
{
}

CBuddylistPanel::~CBuddylistPanel(void)
{
}


BEGIN_MESSAGE_MAP(CBuddylistPanel, CListCtrl)
	ON_WM_CREATE()
	ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
END_MESSAGE_MAP()

int CBuddylistPanel::OnCreate(
					 LPCREATESTRUCT lpCreateStruct 
					 )
{

	int nRet = __super::OnCreate(lpCreateStruct);

	InsertColumn(0, _T("buddy_image"), LVCFMT_CENTER, MainPage_BuddylistPanel_cx/2);
	InsertColumn(1, _T("buddy_name"), LVCFMT_LEFT, MainPage_BuddylistPanel_cx/2);

	return nRet;

}

HRESULT CBuddylistPanel::OnUpdateBuddylist()
{
	IBuddylist *pBuddylist = NULL;
	CAccountInfoMgr::GetInstance()->GetBuddylist(&pBuddylist);

	if (!pBuddylist)
	{
		_ASSERTE(FALSE);
		return E_FAIL;
	}

	int nCount = 0;
	pBuddylist->get_counnt(nCount);
	for (int i = 0 ; i < nCount; ++i)
	{

		BUDDY_INFO info;
		pBuddylist->get_itemAt(i,info);

// 		LV_ITEM lvi;
// 		lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE;
// 		lvi.iItem = i;
// 		lvi.iSubItem = 1;
// 		lvi.pszText = info.strAccoutName.GetBuffer(0);
// 		lvi.iImage = i;
// 		lvi.stateMask = LVIS_STATEIMAGEMASK;
// 		lvi.state = INDEXTOSTATEIMAGEMASK(1);
// 
// 		InsertItem(&lvi);

		LVFINDINFO	findinfo;
		findinfo.flags = LVFI_STRING;
		findinfo.psz = info.strAccoutName.GetBuffer(0);
		int nItem = FindItem(&findinfo);

		if (nItem == -1)
		{
			nItem = InsertItem(0,info.strAccoutName);
		}

		SetItemText(nItem,0,info.strAccoutName);
		if (info.strNick.IsEmpty())
		{
			SetItemText(nItem,1,_T("No nickname"));
		}else
		{
			SetItemText(nItem,1,info.strNick);
		}
	}

	return S_OK;
}

void CBuddylistPanel::OnClick(NMHDR *pNMHDR, LRESULT *pResult)
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
        if(pNMListView->iItem != -1)
        {
			CString strItemText = GetItemText(pNMListView->iItem,0);
			CChatFrameMgr::GetInstance()->OpenChatFrame(strItemText.GetBuffer(0));
		}

        *pResult = 0;

}